class PaymentsController < ApplicationController
#  include ActiveMerchant::Billing::Integrations
  skip_before_filter :verify_authenticity_token
  before_filter :login_required,:only => [:new]
  before_filter :find_user,:only => [:new]

  def new
    @order = Order.find(params[:id])
  end

  def notify
    logger.error("yes alipay came")
    notification = ActiveMerchant::Billing::Integrations::Alipay::Notification.new(request.raw_post)
    logger.error("yes create new notify")
    AlipayTxn.create(:notify_id => notification.notify_id, 
      :total_fee => notification.total_fee, 
      :status => notification.trade_status, 
      :trade_no => notification.trade_no, 
      :received_at => notification.notify_time)

    notification.acknowledge

    @order = Order.find(notification.out_trade_no)

    if @order 
      case notification.status
      when "WAIT_BUYER_PAY"
        #        @order.pend_payment!
      when "WAIT_SELLER_SEND_GOODS"
        @order.set_status_paid
        @order.save
      when "WAIT_BUYER_CONFIRM_GOODS"
        #        @order.confirm_shipment!
      when "TRADE_FINISHED"
        @order.set_status_complete
        @order.save
      else
        logger.error("pay fail = #{notification.out_trade_no}")
      end
    else
      logger.error("Can't order with id = #{notification.out_trade_no}")
    end

    render :nothing
  end


  #  def alipay_ipn
  #    notify = Alipay::Notification.new(request.raw_post)
  #    order = Order.find(notify.order_id)
  #
  #    if notify.acknowledge
  #      #      begin
  #      if notify.complete? and order.total_price.to_s == notify.amount and order.status != 5
  #        order.set_status_complete
  #      else
  #        logger.error("status#{order.total_price}==#{notify.amount}")
  #        logger.error("Failed to verify Alipay's notification, please
  #investigate#{order.total_price}==#{notify.amount},complate=#{notify.complete}")
  #      end
  #      if notify.wait_seller_send_goods? and order.total_price.to_s == notify.amount and order.status != 2
  #        order.set_status_paid
  #      else
  #        logger.error("Failed to verify Alipay's notification, please investigate#{order.total_price}==#{notify.amount}")
  #      end
  #
  #      #      rescue => e
  #      #        order.status = 9
  #      #        raise
  #      #      ensure
  #      Order.transaction do
  #        if order.agent_id
  #          agent = User.find(order.agent_id)
  #          if agent.discount - order.retail_discount > 0
  #            agent.account += order.total_product_price * (agent.discount - order.retail_discount)
  #            agent.save
  #          end
  #        end
  #        order.save
  #      end
  #      #      end
  #    else
  #      logger.error("!acknowledge")
  #    end
  #
  #    render :nothing
  #  end

end
